﻿using Kongt.Common;
using Kongt.IServices;
using Kongt.IServices.QueryModel;
using Kongt.Model;
using Kongt.ServiceProvider;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;

namespace Kongt.Web.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary> 
    public class UserController : BaseUserController
    {
        ICustomService customService = ServiceFactory.Create<ICustomService>();


        // GET: User 用户列表 
        public ActionResult Index(CustomQuery p)
        {

            var pModel = customService.QueryCustomers(p);
            PagedList<Customer> model = new PagedList<Customer>(pModel.Rows, p.PageIndex, p.PageSize, pModel.Count);


            return View(model);
        }


        [HttpPost]
        public ActionResult FindByCustomerId(string customerId)
        {
            var pageModel = customService.QueryCustomers(new IServices.QueryModel.CustomQuery() { CustomerId = customerId });
            if (pageModel.Count > 0)
            {
                var obj = pageModel.Rows.FirstOrDefault();
                return Json(new JStat(new
                {
                    Id = obj.Id,
                    Name = obj.CustomerName,
                    FirstArea = obj.FirstArea,
                    SecondArea = obj.SecondArea,
                    DetailAddress = obj.DetailAddress,
                    WaterTypeName = obj.WaterType?.TypeName,
                    EmployeeName = obj.EmployeeInfo?.NAME,
                    MeterNo = obj.MeterNo,
                    MeterNature = ((Customer.MeterNatureEnum)obj.MeterNature).ToDescription(),
                    CreateDate = obj.CreateDate.ToString("yyyy/MM/dd"),
                    HouseType = ((Customer.HouseTypeEnum)obj.HouseType).ToDescription(),
                    PersonId = obj.PersonId,
                    LinkPhone = obj.LinkPhone,
                    ReadPersonId = obj.ReadPersonId,
                    WaterTypeId = obj.WaterTypeId,
                }));
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = "没有搜索到！" });
            }
        }



        /// <summary>
        /// 增加修改
        /// </summary>
        /// <param name="custom"></param>
        [HttpPost]
        public JsonResult Edit(Customer custom)
        {
            if (ModelState.IsValid)
            {
                if (custom.Id > 0)
                {
                    customService.Update(custom);
                }
                else
                {
                    customService.Create(custom);
                }
                return Json(new JStat());
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = ModelState.Values.First().Errors[0].ErrorMessage });
            }
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="custom"></param>   
        [HttpPost]
        public JsonResult Del(long id)
        {
            customService.Delete(id);
            return Json(new JStat());
        }


        public ActionResult Search(CustomQuery p)
        {
            ViewBag.QueryString = Request.Url.Query;
            return Index(p);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        public ActionResult Export(CustomQuery p)
        {
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //获取list数据 

            var pageModel = customService.QueryCustomers(p);


            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("ID");
            row1.CreateCell(1).SetCellValue("用户编号");
            row1.CreateCell(2).SetCellValue("用户姓名");
            row1.CreateCell(3).SetCellValue("身份证号");
            row1.CreateCell(4).SetCellValue("联系电话");
            row1.CreateCell(5).SetCellValue("区域分布");
            row1.CreateCell(6).SetCellValue("区域名称");
            row1.CreateCell(7).SetCellValue("详细地址");
            row1.CreateCell(8).SetCellValue("水表编号");
            row1.CreateCell(9).SetCellValue("水表初值");
            row1.CreateCell(10).SetCellValue("用户状态");
            row1.CreateCell(11).SetCellValue("房屋类型");
            row1.CreateCell(12).SetCellValue("用水类别");
            row1.CreateCell(13).SetCellValue("水表性质");
            row1.CreateCell(14).SetCellValue(" 分表？");
            row1.CreateCell(15).SetCellValue("抄表人员");
            row1.CreateCell(16).SetCellValue("开户日期");
            row1.CreateCell(17).SetCellValue("备注");
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < pageModel.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                var row = pageModel.Rows[i];
                rowtemp.CreateCell(0).SetCellValue(row.Id.ToString());
                rowtemp.CreateCell(1).SetCellValue(row.CustomerId.ToString());
                rowtemp.CreateCell(2).SetCellValue(row.CustomerName.ToString());
                rowtemp.CreateCell(3).SetCellValue(row.PersonId.ToString());
                rowtemp.CreateCell(4).SetCellValue(row.LinkPhone.ToString());
                rowtemp.CreateCell(5).SetCellValue(row.FirstArea.ToString());
                rowtemp.CreateCell(6).SetCellValue(row.SecondArea.ToString());
                rowtemp.CreateCell(7).SetCellValue(row.DetailAddress.ToString());
                rowtemp.CreateCell(8).SetCellValue(row.MeterNo.ToString());
                rowtemp.CreateCell(9).SetCellValue(row.MeterStart.ToString());
                rowtemp.CreateCell(10).SetCellValue(((Customer.CustomStatEnum)row.CustomerStat).ToDescription());
                rowtemp.CreateCell(11).SetCellValue(((Customer.HouseTypeEnum)row.HouseType).ToDescription());
                rowtemp.CreateCell(12).SetCellValue(row.WaterType?.TypeName);
                rowtemp.CreateCell(13).SetCellValue(((Customer.MeterNatureEnum)row.MeterNature).ToDescription());
                rowtemp.CreateCell(14).SetCellValue(row.ParentId == null ? "-" : "分表");
                rowtemp.CreateCell(15).SetCellValue(row.EmployeeInfo?.NAME);
                rowtemp.CreateCell(16).SetCellValue(row.OpenAccountDate?.ToString("yyyy/MM/dd"));
                rowtemp.CreateCell(17).SetCellValue(row.DESCRIPTION ?? "");

            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", DateTime.Now.Ticks + ".xls");
        }





        public ActionResult OpenAccountSearch(CustomQuery p)
        {
            ViewBag.QueryString = Request.Url.Query;
            return Index(p);
        }


        /// <summary>
        /// 开户信息新增
        /// </summary>
        /// <returns></returns>
        public ActionResult Add_OpenAccountCharge(string customerId)
        {
            var openAccount = new OpenAccountInfo();
            if (!string.IsNullOrEmpty(customerId))
            {
                var pmodel = customService.QueryAccounts(new OpenAccountQuery() { customerId = customerId });
                if (pmodel.Count > 0)
                {
                    openAccount = pmodel.Rows.FirstOrDefault();
                }
            }
            var documents = new List<Document>();
            var documentPagemodel = ServiceFactory.Create<ICommonSetService>().QueryDocument(new QueryBase() { PageSize = 10000 });
            if (documentPagemodel.Count > 0)
            {
                documents = documentPagemodel.Rows;
            }
            ViewBag.documents = documents;
            ViewBag.currentUser = CurrentUser;
            ViewBag.customerId = customerId;
            return View(openAccount);
        }

        [HttpPost]
        public ActionResult GetDocumentsByCustomerId(long customerId)
        {
            var pmodel = customService.QueryAccounts(new OpenAccountQuery() { UserId = customerId });
            if (pmodel.Count > 0)
            {
                var model = pmodel.Rows.FirstOrDefault().OpenAccountDocuments;
                return Json(new JStat(new
                {
                    Documents = model.Select(c => new
                    {
                        DocumentName = c.DocumentName,
                        DocumentUnit = c.DocumentUnit,
                        DocumentPrice = c.DocumentPrice,
                        DocumentNum = c.DocumentNum,
                        DocumentDesc = c.DocumentDesc,
                        TotalPrice = (c.DocumentPrice * c.DocumentNum).ToString("f2"),
                        Id = c.Id
                    }),
                    AllPrice = model.Sum(item => (item.DocumentNum * item.DocumentPrice)).ToString("f2")
                }));
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = "没有材料信息" });
            }

        }


        /// <summary>
        /// 开户信息新增
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("Add_OpenAccountCharge")]
        public ActionResult OpenAccountEdit(OpenAccountInfo account)
        {

            if (!string.IsNullOrEmpty(account.documentsJson))
            {
                account.OpenAccountDocuments = JsonConvert.DeserializeObject<List<OpenAccountDocument>>(account.documentsJson);
            }
            if (account.Id == 0)
            {
                account.CreateDate = DateTime.Now;
            }
            if (ModelState.IsValid)
            {
                if (account.Id > 0)
                {
                    customService.UpdateAccount(account);
                }
                else
                {
                    account.OperatorId = CurrentUser.UserId;
                    customService.CreateAccount(account);
                }
                return RedirectToAction("OpenAccountSearch");
            }
            else
            {
                return Json(new JStat() { Succeed = false, Msg = ModelState.Values.First().Errors[0].ErrorMessage }, JsonRequestBehavior.AllowGet);
            }
        }



    }
}